// Behavior Created by Liferose
#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

using Bots.Grind;
using Buddy.Coroutines;
using CommonBehaviors.Actions;
using Honorbuddy.QuestBehaviorCore;
using Styx;
using Styx.Common;
using Styx.CommonBot;
using Styx.CommonBot.POI;
using Styx.Pathing;
using Styx.CommonBot.Profiles;
using Styx.CommonBot.Routines;
using Styx.Helpers;
using Styx.TreeSharp;
using Styx.WoWInternals;
using Styx.WoWInternals.World;
using Styx.WoWInternals.WoWObjects;

using Action = Styx.TreeSharp.Action;
#endregion


namespace Honorbuddy.Quest_Behaviors.LifeProject.SpecificQuests.Kalimdor.Azshara
{
    [CustomBehaviorFileName(@"LifeProject\14135-UpATree")]
    public class UpATree : QuestBehaviorBase
    {
        #region Constructor and Argument Processing
        public UpATree(Dictionary<string, string> args)
            : base(args)
        {
            QBCLog.BehaviorLoggingContext = this;

            try
            {
                QuestId = 14135;
                QuestRequirementComplete = QuestCompleteRequirement.NotComplete;
                QuestRequirementInLog = QuestInLogRequirement.InLog;
				Waypoint = new WoWPoint(2550.947, -4859.802, 145.2376);
            }

            catch (Exception except)
            {
                // Maintenance problems occur for a number of reasons.  The primary two are...
                // * Changes were made to the behavior, and boundary conditions weren't properly tested.
                // * The Honorbuddy core was changed, and the behavior wasn't adjusted for the new changes.
                // In any case, we pinpoint the source of the problem area here, and hopefully it can be quickly
                // resolved.
                QBCLog.Exception(except);
                IsAttributeProblem = true;
            }
        }

        protected override void EvaluateUsage_DeprecatedAttributes(XElement xElement)
        {
        }

        protected override void EvaluateUsage_SemanticCoherency(XElement xElement)
        {
        }

        public int QuestId { get; private set; }
		public WoWPoint Waypoint { get; private set; }
        public QuestCompleteRequirement QuestRequirementComplete { get; private set; }
        public QuestInLogRequirement QuestRequirementInLog { get; private set; }
        #endregion

        #region Private and Convenience variables
        public LocalPlayer Me { get { return (StyxWoW.Me); } }
        #endregion

		private WoWUnit Sapling
		{
			get
			{
				return ObjectManager.GetObjectsOfType<WoWUnit>()
					.Where(u => (u.Entry == 35162) && !u.IsDead)
					.OrderBy(u => u.Distance).FirstOrDefault();
			}
		}

		private WoWUnit Scout
		{
			get
			{
				return ObjectManager.GetObjectsOfType<WoWUnit>()
					.Where(u => (u.Entry == 35149) && u.IsAlive && (u.CurrentTarget == null || u.CurrentTarget == Me.CharmedUnit))
					.OrderBy(u => u.Distance).FirstOrDefault();
			}
		}

		private bool Buzzsaw()
		{
			return
				Lua.GetReturnVal<bool>("if GetPetActionCooldown(1) == 0 then CastPetAction(1) return 1 else return nil end", 0);
		}

		private bool FlingBlade()
		{
			return
				Lua.GetReturnVal<bool>("if GetPetActionCooldown(2) == 0 then CastPetAction(2) return 1 else return nil end", 0);
		}

        public override void OnStart()
        {
            var isBehaviorShouldRun = OnStart_QuestBehaviorCore(string.Empty);

            if (isBehaviorShouldRun)
            {
                LevelBot.BehaviorFlags &=
                    ~(BehaviorFlags.Combat | BehaviorFlags.Vendor);
            }
        }

        protected override Composite CreateBehavior_CombatOnly()
        {
            return new PrioritySelector(
                new Decorator(context => Query.IsInVehicle(),
                    new ActionAlwaysSucceed())
                );
        }

        protected override Composite CreateMainBehavior()
        {
			return new PrioritySelector(
				new Decorator(context => (Me.IsQuestComplete(QuestId) || !Query.IsInVehicle()),
					new Sequence(
						new Action(context => { BehaviorDone(); })						
						)
					),
				new Decorator(context => Scout != null,
					new PrioritySelector(
						new Decorator(context => !Scout.WithinInteractRange,
								new Action(context => { Navigator.MoveTo(Scout.Location); })
							),
						new Decorator(context => Me.CharmedUnit.IsMoving,
								new Action(context => { WoWMovement.MoveStop(); })							
							),
						new Decorator(context => !SpellManager.GlobalCooldown,
							new Sequence(
								new Action(context => { Scout.Target(); }),
								new Action(context => { Scout.Face(); }),
								new Action(context => Buzzsaw() ? RunStatus.Success : RunStatus.Failure),
								new WaitContinue(TimeSpan.FromMilliseconds(1500), context => false, new ActionAlwaysSucceed()),
								new Action(context => FlingBlade() ? RunStatus.Success : RunStatus.Failure),
								new WaitContinue(TimeSpan.FromMilliseconds(1500), context => false, new ActionAlwaysSucceed())
								)
							)
						)
					),
				new Decorator(context => Sapling != null && Scout == null,
					new PrioritySelector(
						new Decorator(context => !Sapling.WithinInteractRange,
								new Action(context => { Navigator.MoveTo(Sapling.Location); })
							),
						new Decorator(context => Me.CharmedUnit.IsMoving,
								new Action(context => { WoWMovement.MoveStop(); })
							),
						new Decorator(context => !SpellManager.GlobalCooldown,
								new Sequence(
								new Action(context => { Sapling.Target(); }),
								new Action(context => { Sapling.Face(); }),
								new Action(context => Buzzsaw() ? RunStatus.Success : RunStatus.Failure),
								new WaitContinue(TimeSpan.FromMilliseconds(5000), context => false, new ActionAlwaysSucceed())
								)							
							)
						)
					)
				);
        }
    }
}
